<?php

namespace app\admin\controller\wx;

use app\admin\model\wx\WxAccount;
use app\admin\model\wx\WxArticle;
use app\admin\model\wx\WxMediaInfo;
use app\common\controller\AdminController;
use app\common\service\wechat\WechatService;
use EasyAdmin\annotation\ControllerAnnotation;
use EasyAdmin\annotation\NodeAnotation;
use EasyWeChat\Factory;
use think\App;
use think\Db;
use think\facade\View;
use think\Request;

/**
 * @ControllerAnnotation(title="wx_menu")
 */
class WxMenu extends AdminController
{

    use \app\admin\traits\Curd;

    public function __construct(App $app)
    {
        parent::__construct($app);

        $this->model = new \app\admin\model\wx\WxMenu();

    }

    /**
     * 后台微信菜单页面
     * Author:YangXinPeng
     * @return string
     */
    public function menu()
    {
        View::engine()->layout(false);
        return View::fetch();
    }

    /**
     * Author:YangXinPeng
     * 保存微信菜单
     * @param Request $request
     * @return \think\response\Json
     */
    public function addWeixinMenu(Request $request)
    {
        $data = $request->post();
        $menu = $data['menu'];
        $res = WechatService::addList($menu);
        return json($res);
    }

    /**
     * Author:YangXinPeng
     * 删除微信菜单
     */
    public function menuDel()
    {
        $res = WechatService::delList(); // 全部
        if ($res['errcode'] == 0) {
            return $this->result('删除成功');
        } else {
            return $this->result('删除失败', -1);
        }
    }


    /**
     * Author:YangXinPeng
     * 获取对应公众号信息
     * @return \think\Collection
     */
    public function getWxAccount()
    {
        $info = WxAccount::getAccount();
        return $info;
    }

    /**
     * Author:YangXinPeng
     * 查询公众号菜单
     * @param Request $request
     * @return \think\response\Json|void
     */
    public function changeApp(Request $request){
        $appid = $request->post('app_id');
        $menu = WechatService::changeApp($appid);
        if(isset($menu['menu'])){
            $button = $menu['menu'];
          return  json($button);
        }else{
          return   $this->error('失败');
        }

    }

    /**
     * Author:YangXinPeng
     * 获取不同媒体信息
     * @param Request $request
     * @return \think\response\Json
     * @throws \think\db\exception\DataNotFoundException
     * @throws \think\db\exception\DbException
     * @throws \think\db\exception\ModelNotFoundException
     */
    public function getMaterialByType(Request $request){
        $type = $request->post('type');
        $res =  \app\admin\model\wx\WxMedia::where('type',$type)->select()->toArray();
        if($type=='news'){
            foreach ($res as $k=>$v){
                $res[$k]['groupList'] = WxMediaInfo::where('material_id',$v['id'])->select()->toArray();
            }
        }
        return json(['code'=>200,'msg'=>'成功','data'=>$res]);
    }

    /**
     * Author:YangXinPeng
     * 图文上传
     * @param Request $request
     * @return string|\think\response\Json
     * @throws \EasyWeChat\Kernel\Exceptions\InvalidConfigException
     * @throws \GuzzleHttp\Exception\GuzzleException
     */
    public function materialAdd(Request $request)
    {
        if($request->isPost()){
            $data =$request->post('content');
            foreach ($data as $k => $v) {
                $article= new WxArticle($data[$k]);
                $articles[$k] = $article;
            }
            $app = $this->wxClient();
            $res = $app->material->uploadArticle($articles);
            $WxMaterialData = [
                'type'=>'news',
                'media_id'=>$res['media_id'],
            ];
            $material =    $this->getMaterialByMediaId($res['media_id']);
            try {
                $mat= \app\admin\model\wx\WxMedia::create($WxMaterialData);
                //多图文
                foreach ($data as $k=>$v) {
                    $data[$k]['cover'] = \app\admin\model\wx\WxMedia::
                    where('media_id', $data[$k]['thumb_media_id'])
                        ->value('media_url');
                    $data[$k]['local_cover'] = \app\admin\model\wx\WxMedia::
                    where('media_id', $data[$k]['thumb_media_id'])
                        ->value('local_cover');
                    $data[$k]['url'] = $material['news_item'][$k]['url'];
                    $data[$k]['material_id'] = $mat->id;
                    WxMediaInfo::create($data[$k]);
                }
                // 提交事务
                return json(['code'=>200,'msg'=>'上传成功']);
            } catch (\Exception $e) {
                // 回滚事务
                return json(['code'=>400,'msg'=>$e->getMessage()]);
            }
        }
        $params['name'] = 'container';
        $params['content'] = '';
        $view = [
            'info' => [],
            'title' => 'asdasd',
        ];
        View::assign($view);
        return View::fetch();
    }


    public function wxClient()
    {
        $config = config("setting.wechat");
        $app = Factory::officialAccount($config);
        return $app;
    }
    /**
     * Author:YangXinPeng
     * 获取对应素材的媒体ID
     * @param $mediaId
     * @return mixed
     * @throws \EasyWeChat\Kernel\Exceptions\InvalidConfigException
     * @throws \GuzzleHttp\Exception\GuzzleException
     */
    protected function getMaterialByMediaId($mediaId)
    {
        $app = $this->wxClient();
        $resource = $app->material->get($mediaId);
        return $resource;
    }

    /**
     * Author:YangXinPeng
     * 简单上传
     * @return array
     */
    protected function uploads(){
        //获取上传文件表单字段名
        $fileKey = array_keys(request()->file());
        for ($i = 0; $i < count($fileKey); $i++) {
            //获取表单上传文件
            $file = request()->file($fileKey[$i]);
            try {
                $savename = \think\facade\Filesystem::disk('public')->putFile('uploads', $file);
                $path[] =  '/'.$savename;
            } catch (\think\exception\ValidateException $e) {
                $path = '';
                $error = $e->getMessage();
            }
        }
        if (!empty($path)) {
            $result['code'] = 1;
            //分辨是否截图上传，截图上传只能上传一个，非截图上传可以上传多个
            if (request()->param('responseType') == 'json') {
                $result["url"] = $path[0];
            } else {
                $result["url"] = $path[0];
            }
            $result['msg'] = lang('upload success');
            return $result;
        } else {
            //上传失败获取错误信息
            $result['url'] = '';
            $result['msg'] = $error;
            $result['code'] = 0;
            return $result;
        }
    }

    /**
     * Author:YangXinPeng
     * 图片上传
     * @return \think\response\Json
     * @throws \EasyWeChat\Kernel\Exceptions\InvalidArgumentException
     * @throws \EasyWeChat\Kernel\Exceptions\InvalidConfigException
     * @throws \GuzzleHttp\Exception\GuzzleException
     */
    public function imageUpload(){
        $app = $this->wxClient();
        $res = $this->uploads();
        if($res['code']>0){
            //路劲用相对路径
            $result = $app->material->uploadImage('./'.$res['url']);
            $data  = [
                'media_id'=> $result['media_id'],
                'media_url'=> $result['url'],
                'local_cover'=> $res['url'],
                'type'=> 'image',
            ];
            $r = \app\admin\model\wx\WxMedia::create($data);
            if($r){
                $info = $r->toArray();
                $data = ['media_id'=>$info['media_id'],'url'=>$info['media_url']];
                return json(['code'=>200,'msg'=>'上传成功','data'=>$data]);
            }else{
               return json(['code'=>400,'msg'=>'上传失败']);

            }
        }else{
            return json(['code'=>400,'msg'=>'上传失败']);

        }
    }

    /**
     * Author:YangXinPeng
     * 视频上传
     * @throws \EasyWeChat\Kernel\Exceptions\InvalidArgumentException
     * @throws \EasyWeChat\Kernel\Exceptions\InvalidConfigException
     * @throws \GuzzleHttp\Exception\GuzzleException
     */
    public function videoUpload(){
        $app = $this->wxClient();
        $data = $this->request->post();
        if(!$data['url'] || !$data['file_name'] || !$data['des']){
            return json(['code'=>400,'msg'=>'参数错误']);
        }
        $result = $app->material->uploadVideo('.'.$data['url'],$data['file_name'],$data['des']);
        $resource =$app->material->get($result['media_id']);
        if ($resource instanceof \EasyWeChat\Kernel\Http\StreamResponse) {
            // 以内容 md5 为文件名
            $filename =  $resource->save('uploads');
            $down_url = 'http://sx1.51chow.com/uploads/'.$filename;
        }
//        $down_url = 'http://sx1.51chow.com'.$data['url'];
        $datas  = [
            'media_id'=> $result['media_id'],
            'media_url'=> $down_url,
            'local_cover'=> $data['url'],
            'type'=> 'video',
            'file_name'=> $data['file_name'],
            'des'=> $data['des'],
        ];
        $result['url'] = $down_url;
        $r = \app\admin\model\wx\WxMedia::create($datas);
        if($r){
            return json(['code'=>200,'msg'=>'上传成功','data'=>$result]);
        }else{
            return json(['code'=>400,'msg'=>'参数错误']);
        }
    }

    /**
     * Author:YangXinPeng
     * 语音上传
     * @throws \EasyWeChat\Kernel\Exceptions\InvalidArgumentException
     * @throws \EasyWeChat\Kernel\Exceptions\InvalidConfigException
     * @throws \GuzzleHttp\Exception\GuzzleException
     */
    public function voiceUpload(){
        $app = $this->wxClient();
        $res = $this->uploads();
        if($res['code']>0){
            //路劲用相对路径
            $result = $app->material->uploadVoice('./'.$res['url']);
            $resource = $app->material->get($result['media_id']);
            if ($resource instanceof \EasyWeChat\Kernel\Http\StreamResponse) {
                // 以内容 md5 为文件名
               $filename =  $resource->save('uploads');
               $down_url = 'http://sx1.51chow.com/uploads/'.$filename;
            }
            $data  = [
                'media_id'=> $result['media_id'],
                'media_url'=> $down_url,
                'local_cover'=> $res['url'],
                'type'=> 'voice',
            ];
            $result['url'] = $down_url;
            $flag = \app\admin\model\wx\WxMedia::create($data);
            if($flag){
                return json(['code'=>200,'msg'=>'上传成功','data'=>$result]);
            }else{
                return json(['code'=>400,'msg'=>'上传失败']);
            }
        }else{
            return json(['code'=>400,'msg'=>'上传失败']);
        }
    }


    /**
     * Author:YangXinPeng
     * 缩略图上传
     * @throws \EasyWeChat\Kernel\Exceptions\InvalidArgumentException
     * @throws \EasyWeChat\Kernel\Exceptions\InvalidConfigException
     * @throws \GuzzleHttp\Exception\GuzzleException
     */
    public function thumbUpload(){
        $app = $this->wxClient();
        $res = $this->uploads();
        if($res['code']>0){
            //路劲用相对路径
            $result = $app->material->uploadThumb('./'.$res['url']);
            $data  = [
                'media_id'=> $result['media_id'],
                'media_url'=> $result['url'],
                'local_cover'=> $res['url'],
                'type'=> 'image',
            ];
            $r = \app\admin\model\wx\WxMedia::create($data);
            if($r){
                $this->success(lang('upload success'),$result['url']);
            }else{
                $this->error(lang('upload fail'));
            }
        }else{
            $this->error(lang('upload fail'));
        }
    }

    public function UeditUploadImage(){
        $app = $this->wxClient();
        $res = $this->uploads();
        if($res['code']>0){
            //路劲用相对路径
            $result = $app->material->uploadImage('./'.$res['url']);
            $data  = [
                'media_id'=> $result['media_id'],
                'media_url'=> $result['url'],
                'local_cover'=> $res['url'],
                'type'=> 'image',
            ];

            \app\admin\model\wx\WxMedia::create($data);
            $data = ['state'=>'SUCCESS','url'=>$data['media_url']];

        }else{
            $data = ['state'=>'SUCCESS','url'=>''];

        }
        return json_encode($data);

    }

    public function UeditUploadVideo(){
        $app = $this->wxClient();
        $res = $this->uploads();
        if($res['code']>0){
            //路劲用相对路径
            $result = $app->material->uploadVideo('./'.$res['url'],$res['url'],$res['url']);
            $resource = $app->material->get($result['media_id']);
            $data  = [
                'media_id'=> $result['media_id'],
                'media_url'=> $resource['down_url'],
                'local_cover'=> $res['url'],
                'type'=> 'video',
                'file_name'=> $res['url'],
                'des'=> $res['url'],
            ];
            $result['url'] = $resource['down_url'];
           \app\admin\model\wx\WxMedia::create($data);
            $data = ['state'=>'SUCCESS','url'=>$resource['down_url']];
        }else{
            $data = ['state'=>'SUCCESS','url'=>''];
        }
        return json_encode($data);

    }

    public function UeditUploaVoice(){
        $app = $this->wxClient();
        $res = $this->uploads();
        if($res['code']>0){
            //路劲用相对路径
            $result = $app->material->uploadVoice('./'.$res['url']);
            $resource = $app->material->get($result['media_id']);
            $data  = [
                'media_id'=> $result['media_id'],
                'media_url'=> $resource['down_url'],
                'local_cover'=> $res['url'],
                'type'=> 'image',
            ];
            $result['url'] = $resource['down_url'];
            \app\admin\model\wx\WxMedia::create($data);
            $data = ['state'=>'SUCCESS','url'=>$resource['down_url']];
        }else{
            $data = ['state'=>'SUCCESS','url'=>''];
        }
        return json_encode($data);
    }

    public function getListImage(){
        $list = \app\admin\model\wx\WxMedia::where('type','image')->select();
        $data = ['state'=>'SUCCESS','start'=>0,'total'=>count($list),'list'=>[]];
        if($list){
            foreach ($list as $k=>$v) {
                $data['list'][$k]['url'] = $v['media_url'];
                $data['list'][$k]['mtime'] = time();
            }
        }
        return json_encode($data);
    }


    /**
     * Author:YangXinPeng
     * 视频专用上传
     * @param Request $request
     * @return array
     */
    public function videoUploads(Request $request){
        //获取上传文件表单字段名
        $fileKey = array_keys(request()->file());
        for ($i = 0; $i < count($fileKey); $i++) {
            //获取表单上传文件
            $file = request()->file($fileKey[$i]);
            try {
                $savename = \think\facade\Filesystem::disk('public')->putFile('uploads', $file);
                $path[] = '/' . $savename;
            } catch (\think\exception\ValidateException $e) {
                $path = '';
                $error = $e->getMessage();
            }
        }
        if (!empty($path)) {
            $result['code'] = 1;
            //分辨是否截图上传，截图上传只能上传一个，非截图上传可以上传多个
            if ($request->param('responseType') == 'json') {
                $result["url"] = $path[0];
            } else {
                $result["url"] = $path;
            }
            $result['msg'] = 'upload success';
            return $result;
        } else {
            //上传失败获取错误信息
            $result['url'] = '';
            $result['msg'] = $error;
            $result['code'] = 0;
            return $result;
        }
    }


}